# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.
from django.views import View
from .models import BookInfo
from django import http

class BookView(View):

    def get(self,request):
        book = BookInfo.objects.all()

        return http.JsonResponse(book)


    # 增加
    def post(self,request):

        # 获取输入的数据
        book_btirle = request.POST.get('book.btitle')
        book_people = request.POST.get('book.people')
        bpub_data = request.POST.get('book.bpub_data')
        book_bread = request.POST.get('book.bread')
        book_bcomment = request.POST.get('book.bcomment')

        try:
            book = BookInfo()
            book.btitle = book_btirle
            book.people = book_people
            book.bpub_data = bpub_data
            book.bread = book_bread
            book.bcomment = book_bcomment
            book.save()

            return http.JsonResponse('添加成功')
        except Exception as e:

            return http.JsonResponse('添加失败')

    # 删除
    def delete(self,request):

        # 获取要删除的数据
        del_id = request.POST.get('id')
        try:
            book = BookInfo.objects.get(id=del_id)
            book.delete()

            return http.JsonResponse('删除成功')
        except Exception as e:
            return http.JsonResponse('删除失败')


    # 修改
    def put(self,request):

        # 获取要修改图书的id
        put_id = request.POST.get('id')

        # 查找id所对应的书
        try:
            book = BookInfo.objects.get(id=put_id)
            # 获取修改的信息
            book_btirle = request.POST.get('book.btitle')
            book_people = request.POST.get('book.people')
            bpub_data = request.POST.get('book.bpub_data')
            book_bread = request.POST.get('book.bread')
            book_bcomment = request.POST.get('book.bcomment')

            # 修改
            book.btitle = book_btirle
            book.people = book_people
            book.bpub_data = bpub_data
            book.bread = book_bread
            book.bcomment = book_bcomment
            book.save()

            return http.JsonResponse('修改成功')
        except Exception as e:
            return http.JsonResponse('修改失败')

